#include "Util/logc.h"
#include "ADecoderManager.h"

namespace Media{

ADecoderManager::Ptr ADecoderManager::Instance(){
    static auto ptr = std::make_shared<ADecoderManager>();
    return ptr;
}
    
    ADecoderManager::ADecoderManager(){
        for(EncChannel i = 0; i< MAX_ENCODER_NUM; i++){
            m_encoders[i] = false;
        }
    }
    
    ADecoderManager::~ADecoderManager(){

    }

    bool ADecoderManager::CreateDecoder(ADecoder::Ptr& ptr){
        std::lock_guard<std::recursive_mutex> guard(m_mux);
        EncChannel chan;
        if(getAvailableChannel(chan)){
            ptr = std::make_shared<ADecoder>(chan);
            m_encoders[chan] = true;
            errorf("CreateDecoder success");
            return true;
        }
        
        errorf("CreateDecoder fail");
        return false;
    }
    
    bool ADecoderManager::ReleaseDecoder(const ADecoder::Ptr& ptr){
        std::lock_guard<std::recursive_mutex> guard(m_mux);
        if(ptr){
            ptr->Stop();
            EncChannel chan = ptr->GetChannel();
            if(m_encoders.find(chan) != m_encoders.end()){
                m_encoders[chan] = false;
            }
        }
        return true;
    }

    bool ADecoderManager::getAvailableChannel(EncChannel& channel){
        std::lock_guard<std::recursive_mutex> guard(m_mux);

        for(auto [key, val]: m_encoders){
            if(!val){
                channel = key;
                return true;
            }
        }
        return false;
    }


}